<template>
  <el-table :data="foodStore.foodRecipeDialog.data.materialList"
            border stripe class="material-table">
    <el-table-column type="index" align="center" width="90">
      <template #header>
        <el-button type="primary" @click="handleAddClick">新增</el-button>
      </template>
    </el-table-column>
    <el-table-column prop="type" label="类型" align="center" min-width="10%"/>
    <el-table-column prop="name" label="名称" align="center" min-width="20%"/>
    <el-table-column prop="amount" label="分量" align="center" min-width="20%"/>
    <el-table-column label="操作" align="center" width="100">
      <template #default="scope">
        <el-button type="primary" text
                   @click="handleEditClick(scope.$index, scope.row)">编辑</el-button>
        <el-button type="danger" text
                   @click="handleDeleteClick(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script setup lang="ts">
import { useFoodStore } from '@/store/food.ts'
import { IFoodMaterial } from '@/types/food.ts'
import { deepCopyObject } from 'vue3-common/utils/dataUtil'
import { commonElMessageBox } from 'vue3-common/utils/elUtil'

const foodStore = useFoodStore()

const handleAddClick = () => {
  foodStore.foodMaterialApiType = 'ADD'
  foodStore.foodMaterialDialog = {
    title: '新增食材',
    visible: true,
    data: foodStore.getEmptyFoodMaterial()
  }
}

const handleEditClick = (index: number, material: IFoodMaterial) => {
  foodStore.editFoodMaterialIndex = index
  foodStore.foodMaterialApiType = 'UPDATE'
  foodStore.foodMaterialDialog = {
    title: '编辑食材',
    visible: true,
    data: deepCopyObject(material)
  }
}

const handleDeleteClick = (index: number, material: IFoodMaterial) => {
  foodStore.foodMaterialApiType = 'DELETE'
  commonElMessageBox(`确认删除该食材: ${material.name}?`).then(() => {
    foodStore.foodRecipeDialog.data.materialList.splice(index, 1)
  })
}
</script>
